/**
 * ====================================================================
 *
 *  Copyright 1999-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * .
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 * 
 * @author Christian
 * @since
 * @version 
 * @Date 17.04.2014
 */
package de.sisoft.gcjack.communication.asyncstask;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import de.sisoft.gcjack.R;
import de.sisoft.gcjack.exception.NoResultFoundException;
import de.sisoft.gcjack.interfaces.AsyncResponse;
import de.sisoft.gcjack.model.AsyncResult;
import de.sisoft.gcjack.model.GeoCache;

/**
 * DefaultAsyncTask is an abstract parent class for every AsyncTask used in this
 * application. It handles network controlling tasks and informs the user about
 * his/her network status.
 * 
 * @param <P>
 *            The {@link List} of Params typed P which should be processed
 * @param <I>
 *            The {@link List} of Progress values - normally typed by an Integer
 * @param <F>
 *            The return value - in this Application an Object which extends
 *            {@link AsyncResult}
 */
public abstract class DefaultAsyncTask<P, I, F> extends AsyncTask<P, I, F> {
    protected AsyncResponse callingActivity;
    private AlertDialog errorDialog;

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
	super.onPreExecute();

	if (!isNetworkAvailable()) {
	    this.cancel(true);
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onProgressUpdate(Progress[])
     */
    @Override
    protected void onProgressUpdate(I... progress) {
	// do some progress update stuff here
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(F result) {
	// do some stuff here if a task has finished!
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.os.AsyncTask#onCancelled(java.lang.Object)
     */
    @Override
    protected void onCancelled() {
	super.onCancelled();
	AlertDialog.Builder builder = new AlertDialog.Builder(callingActivity.getActivity(), 2);
	builder.setTitle(callingActivity.getActivity().getString(R.string.error_title));
	builder.setIcon(R.drawable.dialog_warning_icon);
	builder.setMessage(callingActivity.getActivity().getString(
			R.string.no_network_aviable_message));
	builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.cancel();
		}

	});
	AlertDialog errorDialog = builder.create();
	errorDialog.show();
    }

    /**
     * Sets the delegate Activity as member variable in this {@link AsyncTask}
     * 
     * @param callActivity
     *            An Activity which implements the Interface
     *            {@link AsyncResponse}
     */
    public void setCallActivity(AsyncResponse callActivity) {
	this.callingActivity = callActivity;
    }

    private boolean isNetworkAvailable() {
	ConnectivityManager cm = (ConnectivityManager) callingActivity
		.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo networkInfo = cm.getActiveNetworkInfo();
	// if no network is available networkInfo will be null
	// otherwise check if we are connected
	if (networkInfo != null && networkInfo.isConnected()) {
	    return true;
	}
	return false;
    }

}
